package org.vectrics.recruiter.struts.admin.job;

import java.util.List;

import javax.servlet.jsp.JspException;

import org.apache.struts.action.ActionMessages;
import org.vectrics.employee.Employee;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.job.JobFunction;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;

/**
 * @author pgoette
 * Action encargado de borrar el Function
 */
public class DeleteFunctionAction extends VectricsStrutsAction {


	@Override
	protected String doExecute(VectricsActionData actionData)
			throws JspException {
		
		String forward = "success";
		String code = actionData.getRequest().getParameter("functionCode");
		
		if (code != null) {
			JobFunction function = RecruitServiceLocator.getJobProvider().findFunction(code);
			// Recupero los job
			List<Job> jobs = RecruitServiceLocator.getJobProvider().findJobs();
			for (Job job : jobs){
				// Si un job usa el function genero un error y salgo.
				if (job.getFunction().getCode().equals(function.getCode())) {
					actionData.addError(ActionMessages.GLOBAL_MESSAGE, "error.delete.function");
					return forward;
				}
			}
			
			// Busco todos los empleados
			List<Employee> employees = RecruitServiceLocator.getCompanyService().findAllEmployees();
			
			for (Employee employee: employees) {
				// Si un empleado usa el function genero un error y salgo.
				if ((employee.getFunction()!=null)
						&&(employee.getFunction().getCode().equals(function.getCode()))) {
					actionData.addError(ActionMessages.GLOBAL_MESSAGE, "error.delete.function");
					return forward;
				}
			}
			
			// Borro el Function
			RecruitServiceLocator.getJobProvider().deleteJobFunction(function);
		} 
		
		return forward;
	}

}
